<?php

	$search_url = "http://search.twitter.com/search.json";
	// $keywords = "jurina matsui";
	if($_POST['keywords']!=""){
		$keywords = $_POST['keywords'];
	} else {
		$keywords = "akb48";
	}
	$rpp = 8;
	$url = $search_url . "?q=" . urlencode($keywords) . "&rpp=" . $rpp;
	
	$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);
    curl_close($ch);

	// print $result;
	// print_r(json_decode($result,TRUE));
	// var_dump(json_decode($result,TRUE));	
	$t_array = json_decode($result, TRUE); // retrieval from twitter REST API
	$return_array = array(); //return to front-end
	
	foreach($t_array['results'] as $count => $data_arr) {
		// echo $count;
		$profile_name = $data_arr['from_user'];
		$profile_img_url = $data_arr['profile_image_url'];
		$text = $data_arr['text'];
		$create_time = $data_arr['created_at'];		
		$user_location = getLoc($profile_name);
		
		$tweet = array(
				'name' => $profile_name,
				'img'  => $profile_img_url,
				'time' => $create_time,
				'loc'  => $user_location,
				'text' => $text );
		
		$return_array[] = $tweet; // push to the end of array
		// echo "User Name: " . $profile_name . "--Text: ". $text . "--Loc: " . $user_location . "<br>";
	}

	// print_r($return_array);
	echo json_encode($return_array);
	
	
	// retrieve user location
	function getLoc( $screen_name = "" ) {
		$user_show_url = "http://api.twitter.com/1/users/show.json?screen_name=";
		$url = $user_show_url . $screen_name;
		$ch_l = curl_init();
	    curl_setopt($ch_l, CURLOPT_URL, $url);
	    curl_setopt($ch_l, CURLOPT_RETURNTRANSFER, 1);
	    $user_show = curl_exec($ch_l);
	    curl_close($ch_l);		

		$user_show_arr = json_decode($user_show, true);
		return $user_show_arr['location'];
	}

/*
	Containing a word: http://search.twitter.com/search.atom?q=twitter
	From a user: http://search.twitter.com/search.atom?q=from%3Aal3x
*/

//	private static final String URLSTR = "http://search.twitter.com/search.atom";
//	private static final String USER_URL = "http://twitter.com/users/show/";	

?>